import 'dart:convert';

import 'package:im_app/im/uploadAndDownload/FileDownloadService.dart';
import 'package:im_app/im/util/ImSingleton.dart';
import 'package:logger/logger.dart';

import '../../dao/ImMessageDao.dart';
import '../../service/MessageReceiveService.dart';
import '../../uploadAndDownload/UploadAndDownloadDto.dart';
import '../../util/UiUtil.dart';
import '../dto/base/Resp.dart';
import '../dto/business/Message.dart';
import '../dto/business/PullData.dart';
import '../dto/business/SendData.dart';
import 'InitRouter.dart';

class MessageConsumerRouter {

  final _logger = Logger(printer: PrettyPrinter(),);

  void initCallback(Map<String, CallbackData> callbackMap) {
    callbackMap.putIfAbsent("serverMessage", ()=> CallbackData(decodeFunction: MessageObject.fromJson, doFunction: receiveMessage));
    callbackMap.putIfAbsent("serverMessages", ()=> CallbackData(decodeFunction: MessageObject.fromJson, doFunction: receiveMessages));
    callbackMap.putIfAbsent("serverReadMessage", ()=> CallbackData(decodeFunction: MessageReadReq.fromJson, doFunction: receiveReadMessage));
    callbackMap.putIfAbsent("serverWithdrawMessage", ()=> CallbackData(decodeFunction: MessageWithdrawReq.fromJson,
        doFunction: receiveWithdrawMessage));
    callbackMap.putIfAbsent("serverRedirectFileUploadSuccess", ()=> CallbackData(decodeFunction: FileUploadSuccessReq.fromJson,
        doFunction: receiveFileUploadSuccessMessage));
  }

  /// 接受服务端消息
  Future<OkResp> receiveMessage(MessageObject messageObject) async {
    _logger.i("receive message: ${jsonEncode(messageObject)}");
    var startTime = DateTime.now();
    String userId = ImSingleton.getInstance().session.userId!;

    MessageReceiveService messageReceiveService = MessageReceiveService();
    var imMessage = await messageReceiveService.handleReceiveMessage(userId, messageObject);

    UiUtil.uiShowMessage(imMessage);

    _logger.i("receive message end, time: ${DateTime.now().millisecond - startTime.millisecond}", time: DateTime.now());
    return OkResp(coder: 0, successDataTime: DateTime.now());
  }

  /// 接受服务端多个消息
  Future<void> receiveMessages(MessageListItem messageListItem) async {
    _logger.i("receive message: ${jsonEncode(messageListItem)}");
    for (MessageObject messageObject in messageListItem.messageObjectList) {
      await receiveMessage(messageObject);
    }
    _logger.i("receive messages end");
  }

  /// 接受服务端多个消息已读事件
  void receiveReadMessage(MessageReadReq messageReadReq) async {
    _logger.i("receive read message: ${jsonEncode(messageReadReq)}");
    String userId = ImSingleton.getInstance().session.userId!;
    MessageReceiveService messageReceiveService = new MessageReceiveService();
    messageReceiveService.handleReadMessages(userId, messageReadReq.messageIds);

    _logger.i("receive read message end");
  }

  /// 接受服务端的消息撤回事件
  Future<OkResp> receiveWithdrawMessage(MessageWithdrawReq messageWithdrawReq) async {
    _logger.i("receive withdraw message: ${jsonEncode(messageWithdrawReq)}");
    String userId = ImSingleton.getInstance().session.userId!;
    MessageReceiveService messageReceiveService = MessageReceiveService();
    messageReceiveService.handleWithdrawMessages(userId, messageWithdrawReq.messageIds);

    _logger.i("receive withdraw message end");
    return OkResp(coder: 0, successDataTime: DateTime.now());
  }

  /// 接受服务端文件上传成功的通知
  void receiveFileUploadSuccessMessage(FileUploadSuccessReq fileUploadSuccessReq) async {
    _logger.i("receive file upload success message: ${jsonEncode(fileUploadSuccessReq)}");
    var userId = ImSingleton.getInstance().session.userId!;

    var messageDao = ImMessageDao();
    var message = await messageDao.getByServerIdAndUserId(fileUploadSuccessReq.messageId, userId);
    await messageDao.loadMessageOtherInfo([message!]);
    var ip = ImSingleton.getInstance().session.getData("im_ip") as String;
    await FileDownloadService.downFile(message!, (FileDownloadResult downloadResult) {
      if (downloadResult.isSuccess) {

      }
    }, ip);
    _logger.i("receive file upload success message end");
  }
}